<template>
  <div class="page-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="服务名称" prop="serviceName">
        <el-input
          v-model="queryParams.serviceName"
          placeholder="请输入服务名称"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="服务状态"
          clearable
          style="width: 178px"
        >
          <el-option
            v-for="dict in dict.type.serve_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
          >新增服务</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['servicess:orders:remove']"
          >批量删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="ID"
        align="center"
        key="id"
        prop="id"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="缩略图"
        align="center"
        key="thumbnail"
        prop="thumbnail"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-image
            :src="scope.row.thumbnail"
            :preview-src-list="[scope.row.thumbnail]"
            fit="cover"
            style="width: 50px; height: 50px; border-radius: 4px"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="服务名称"
        align="center"
        key="serviceName"
        prop="serviceName"
        v-if="columns[2].visible"
        width="120"
      />
      <el-table-column
        label="基础价格"
        align="center"
        key="basePrice"
        prop="basePrice"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="市场价格"
        align="center"
        key="marketPrice"
        prop="marketPrice"
        v-if="columns[4].visible"
      />
      <el-table-column
        label="销量"
        align="center"
        key="salesCount"
        prop="salesCount"
        v-if="columns[5].visible"
      />
      <el-table-column
        label="浏览量"
        align="center"
        key="viewCount"
        prop="viewCount"
        v-if="columns[6].visible"
      />
      <el-table-column
        label="状态"
        align="center"
        key="status"
        prop="status"
        v-if="columns[7].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['servicess:orders:query']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['servicess:orders:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['servicess:orders:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input
                v-model="form.serviceName"
                placeholder="请输入服务名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基础价格" prop="basePrice">
              <el-input-number
                v-model="form.basePrice"
                :precision="2"
                :step="0.1"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="市场价格" prop="marketPrice">
              <el-input-number
                v-model="form.marketPrice"
                :precision="2"
                :step="0.1"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序值" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="缩略图" prop="thumbnail">
          <image-upload v-model="form.thumbnail" :limit="1" />
        </el-form-item>
        <el-form-item label="图片集" prop="images">
          <image-upload v-model="form.images" :limit="5" />
        </el-form-item>
        <el-form-item label="简短描述" prop="shortDescription">
          <el-input
            v-model="form.shortDescription"
            type="textarea"
            placeholder="请输入简短描述"
          />
        </el-form-item>
        <el-form-item label="详细描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入详细描述"
          />
        </el-form-item>
        <el-form-item label="服务流程" prop="serviceProcess">
          <el-input
            v-model="form.serviceProcess"
            type="textarea"
            :rows="4"
            placeholder="请输入服务流程说明"
          />
        </el-form-item>
        <el-form-item label="建议车型" prop="suggestedCarModels">
          <el-select
            v-model="form.suggestedCarModels"
            multiple
            placeholder="请选择建议车型"
          >
            <el-option label="小型车" value="small" />
            <el-option label="中型车" value="medium" />
            <el-option label="大型车" value="large" />
            <el-option label="SUV" value="suv" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input
            v-model="form.tags"
            placeholder="请输入标签，多个以逗号分隔"
          />
        </el-form-item>
        <el-form-item label="服务状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="服务属性">
          <el-checkbox-group v-model="form.serviceAttributes">
            <el-checkbox label="isFeatured">推荐</el-checkbox>
            <el-checkbox label="isNew">新服务</el-checkbox>
            <el-checkbox label="isHot">热门</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 服务详情对话框 -->
    <el-dialog
      title="服务详情"
      :visible.sync="detailOpen"
      width="780px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="服务名称">{{
          detail.serviceName
        }}</el-descriptions-item>
        <el-descriptions-item label="基础价格"
          >¥{{ detail.basePrice }}</el-descriptions-item
        >
        <el-descriptions-item label="市场价格"
          >¥{{ detail.marketPrice }}</el-descriptions-item
        >
        <el-descriptions-item label="排序值">{{
          detail.sortOrder
        }}</el-descriptions-item>
        <el-descriptions-item label="销量">{{
          detail.salesCount
        }}</el-descriptions-item>
        <el-descriptions-item label="浏览量">{{
          detail.viewCount
        }}</el-descriptions-item>
        <el-descriptions-item label="服务状态">
          <el-tag :type="detail.status === 0 ? 'success' : 'info'">
            {{ detail.status === 1 ? "上架" : "下架" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          detail.createdAt
        }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">图片信息</el-divider>
      <div class="image-container">
        <div class="thumbnail">
          <h4>缩略图</h4>
          <el-image
            :src="detail.thumbnail"
            :preview-src-list="[detail.thumbnail]"
            fit="cover"
            style="width: 200px; height: 200px"
          >
          </el-image>
        </div>
        <div class="image-gallery">
          <h4>图片集</h4>
          <el-image
            v-for="(url, index) in detail.images"
            :key="index"
            :src="url"
            :preview-src-list="detail.images"
            fit="cover"
            style="width: 120px; height: 120px; margin: 5px"
          >
          </el-image>
        </div>
      </div>

      <el-divider content-position="left">描述信息</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="简短描述">{{
          detail.shortDescription
        }}</el-descriptions-item>
        <el-descriptions-item label="详细描述">{{
          detail.description
        }}</el-descriptions-item>
        <el-descriptions-item label="服务流程">{{
          detail.serviceProcess
        }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">其他信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="建议车型">
          <el-tag
            v-for="model in detail.suggestedCarModels"
            :key="model"
            style="margin-right: 5px"
          >
            {{ model }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="标签">
          <el-tag
            v-for="tag in detail.tags ? detail.tags.split(',') : []"
            :key="tag"
            type="success"
            style="margin-right: 5px"
          >
            {{ tag }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="服务属性">
          <el-tag
            v-if="detail.isFeatured"
            type="warning"
            style="margin-right: 5px"
            >推荐</el-tag
          >
          <el-tag v-if="detail.isNew" type="success" style="margin-right: 5px"
            >新服务</el-tag
          >
          <el-tag v-if="detail.isHot" type="danger" style="margin-right: 5px"
            >热门</el-tag
          >
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import {
  listServes,
  deleteById,
  deleteByIds,
  updateService,
  getService,
  addService,
} from "@/api/stores/service";
import { MessageBox } from "element-ui";

export default {
  name: "Serve",
  dicts: ["serve_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单列表数据
      orderList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceName: undefined,
        status: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `ID`, visible: true },
        { key: 1, label: `缩略图`, visible: true },
        { key: 2, label: `服务名称`, visible: true },
        { key: 3, label: `基础价格`, visible: true },
        { key: 4, label: `市场价格`, visible: true },
        { key: 5, label: `销量`, visible: true },
        { key: 6, label: `浏览量`, visible: true },
        { key: 7, label: `状态`, visible: true },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        id: undefined,
        serviceName: undefined,
        thumbnail: undefined,
        images: [],
        shortDescription: undefined,
        description: undefined,
        basePrice: 0,
        marketPrice: 0,
        suggestedCarModels: [],
        serviceProcess: undefined,
        isFeatured: 0,
        isNew: 0,
        isHot: 0,
        tags: undefined,
        sortOrder: 0,
        status: 1,
        serviceAttributes: [],
      },
      // 表单校验
      rules: {
        serviceName: [
          { required: true, message: "服务名称不能为空", trigger: "blur" },
        ],
        basePrice: [
          { required: true, message: "基础价格不能为空", trigger: "blur" },
        ],
        thumbnail: [
          { required: true, message: "缩略图不能为空", trigger: "change" },
        ],
        shortDescription: [
          { required: true, message: "简短描述不能为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "详细描述不能为空", trigger: "blur" },
        ],
        serviceProcess: [
          { required: true, message: "服务流程不能为空", trigger: "blur" },
        ],
      },
      // 详情弹出层
      detailOpen: false,
      // 详情数据
      detail: {
        serviceName: "",
        thumbnail: "",
        images: [],
        shortDescription: "",
        description: "",
        basePrice: 0,
        marketPrice: 0,
        suggestedCarModels: [],
        serviceProcess: "",
        isFeatured: 0,
        isNew: 0,
        isHot: 0,
        tags: "",
        sortOrder: 0,
        salesCount: 0,
        viewCount: 0,
        status: 1,
        createdAt: "",
        updatedAt: "",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询服务列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
      };
      listServes(params)
        .then((response) => {
          console.log("服务列表响应数据：", response);
          if (response.code === 200) {
            this.orderList = response.rows;
            this.total = response.total;
          } else {
            this.$modal.msgError(response.msg || "获取服务列表失败");
          }
        })
        .catch((error) => {
          console.error("获取服务列表出错：", error);
          this.$modal.msgError("获取服务列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务";
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const serviceIds = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除选中的服务数据？")
        .then(() => {
          if (row.id) {
            // 单个删除
            return deleteById(row.id);
          } else {
            // 批量删除
            return deleteByIds(this.ids.join(","));
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 查看按钮操作 */
    handleView(row) {
      // 处理图片数据
      // 确保 detail 对象存在
      this.detail = { ...row }; // 初始化 detail 对象

      if (this.detail.image) { // 使用 detail.image
        try {
          const parsedImages = JSON.parse(this.detail.image);
          this.detail.images = Array.isArray(parsedImages)
            ? parsedImages
            : [this.detail.image];
        } catch (e) {
          console.error('解析图片数据失败:', e);
          this.detail.images = [this.detail.image];
        }
      } else {
        this.detail.images = [];
      }

      // 处理建议车型数据
      if (this.detail.suggestedCarModels) { // 使用 detail.suggestedCarModels
        try {
          this.detail.suggestedCarModels = JSON.parse(this.detail.suggestedCarModels);
        } catch (e) {
          console.error('解析建议车型数据失败:', e);
          this.detail.suggestedCarModels = [];
        }
      } else {
        this.detail.suggestedCarModels = [];
      }

      // 设置其他详情数据
      this.detail.createdAt = row.createTime || "";
      this.detail.updatedAt = row.updateTime || "";

      this.detailOpen = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "serve/services/export",
        {
          ...this.queryParams,
        },
        `serve_${new Date().getTime()}.xlsx`
      );
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      console.log('正在获取服务详情，ID:', id);
      getService(id)
        .then((response) => {
          console.log('获取服务详情响应:', response);
          // 直接处理返回的数据，因为详情接口没有 code 字段
          this.form = response; // 直接使用 response 更新 form
          // 处理图片数据
          if (this.form.images) {
            try {
              // 尝试解析JSON
              const parsedImages = JSON.parse(this.form.images);
              this.form.images = Array.isArray(parsedImages)
                ? parsedImages
                : [this.form.images];
            } catch (e) {
              console.error('解析图片数据失败:', e);
              // 如果不是JSON格式，则作为单个图片URL处理
              this.form.images = [this.form.images];
            }
          } else {
            this.form.images = [];
          }
          // 处理建议车型数据
          if (this.form.suggestedCarModels) {
            try {
              this.form.suggestedCarModels = JSON.parse(
                this.form.suggestedCarModels
              );
            } catch (e) {
              console.error('解析建议车型数据失败:', e);
              this.form.suggestedCarModels = [];
            }
          }
          // 处理服务属性
          this.form.serviceAttributes = [];
          if (this.form.isFeatured)
            this.form.serviceAttributes.push("isFeatured");
          if (this.form.isNew) this.form.serviceAttributes.push("isNew");
          if (this.form.isHot) this.form.serviceAttributes.push("isHot");
          this.open = true;
          this.title = "修改服务";
        })
        .catch((error) => {
          console.error("获取服务详情出错：", error);
          this.$modal.msgError("获取服务详情失败，请检查网络连接或联系管理员");
        });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        serviceName: undefined,
        thumbnail: undefined,
        images: [],
        shortDescription: undefined,
        description: undefined,
        basePrice: 0,
        marketPrice: 0,
        suggestedCarModels: [],
        serviceProcess: undefined,
        isFeatured: 0,
        isNew: 0,
        isHot: 0,
        tags: undefined,
        sortOrder: 0,
        status: 1,
        serviceAttributes: [],
      };
      this.resetForm("form");
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 处理服务属性
          this.form.isFeatured = this.form.serviceAttributes.includes(
            "isFeatured"
          )
            ? 1
            : 0;
          this.form.isNew = this.form.serviceAttributes.includes("isNew")
            ? 1
            : 0;
          this.form.isHot = this.form.serviceAttributes.includes("isHot")
            ? 1
            : 0;

          // 将 suggestedCarModels 数组转换为 JSON 字符串
          if (Array.isArray(this.form.suggestedCarModels)) {
            this.form.suggestedCarModels = JSON.stringify(
              this.form.suggestedCarModels
            );
          }

          // 处理图片数组
          if (Array.isArray(this.form.images)) {
            this.form.images = JSON.stringify(this.form.images);
          } else if (!this.form.images) {
            this.form.images = "[]"; // 如果没有图片，设置为空数组的JSON字符串
          }

          if (this.form.id) {
            updateService(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addService(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 状态修改 */
    handleStatusChange(row) {
      // 修改提示文本的逻辑，使其显示服务当前的上下架状态
      let text = row.status === 1 ? "上架" : "下架";
      MessageBox.confirm('确认要"' + text + '""' + row.serviceName + '"吗？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 发送更新请求
          return updateService(row);
        })
        .then(() => {
          this.$message.success(text + "成功");
        })
        .catch(() => {
          // 如果取消或更新失败，将前端的状态恢复回点击之前的值
          row.status = row.status === 1 ? 0 : 1; // 保持原样，因为这是恢复逻辑
        });
    },
  },
};
</script>

<style>
.card-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-item i {
  font-size: 40px;
  margin-right: 15px;
}

.card-content {
  display: flex;
  flex-direction: column;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
}

.card-label {
  font-size: 14px;
  color: #606266;
}

.page-container {
  margin-top: 20px;
  padding: 0 20px;
}

.mb20 {
  margin-bottom: 20px;
}

.image-container {
  padding: 20px;
}

.thumbnail {
  margin-bottom: 20px;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-divider {
  margin: 20px 0;
}
</style>

